package com.jason.apps.buyer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.HomeActivity;
import com.apps.realtyportal.LoginActivity;
import com.apps.realtyportal.R;
import com.ipaulpro.afilechooser.utils.FileUtils;
import com.jason.apps.alert.EmptyAlert;

public class RegisterBuyer extends SherlockFragmentActivity {

	public EditText fname;
	public EditText lname;
	public EditText email;
	public EditText mobile;
	public EditText landline;
	public EditText bday;
	public EditText username;
	public EditText password;
	public EditText filepath;
	public Button register;
	public Button browse;
	public Spinner type;
	public ImageButton cal;

	String host = "property-portal.uphero.com";
	String ftpuser = "a5596663";
	String ftppass = "ranger123";
	String saveLocation = "/public_html";
	String folderLocation = "/image/";

	FTPClient con = null;
	private static final int REQUEST_CODE = 1;

	SherlockFragmentActivity fa;
	ConsumeWebService consume = new ConsumeWebService();
	private ActionBar actionbar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lead_registration);
		actionbar = getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setDisplayShowTitleEnabled(false);

		fname = (EditText) this.findViewById(R.id.lead_fname);
		lname = (EditText) this.findViewById(R.id.lead_lname);
		email = (EditText) this.findViewById(R.id.lead_email);
		mobile = (EditText) this.findViewById(R.id.lead_mobile);
		landline = (EditText) this.findViewById(R.id.lead_landLine);
		username = (EditText) this.findViewById(R.id.lead_username);
		password = (EditText) this.findViewById(R.id.lead_password);
		filepath = (EditText) this.findViewById(R.id.lead_filepath);
		register = (Button) this.findViewById(R.id.lead_btnRegister);

		register.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if ((!fname.getText().toString().trim().equals(""))
						&& (!lname.getText().toString().trim().equals(""))
						&& (!email.getText().toString().trim().equals(""))
						&& (!username.getText().toString().trim().equals(""))
						&& (!password.getText().toString().trim().equals(""))) {
					new Create().execute();
				} else {
					FragmentManager fm = getSupportFragmentManager();
					EmptyAlert alert = new EmptyAlert();
					alert.show(fm, "Alert_Dialog");
				}
			}
		});

	}

	public void setUrl(String file) {
		filepath.setText(file);
	}

	public void BrowseLead(View v) {
		Intent target = FileUtils.createGetContentIntent();
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));

		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					final Uri uri = data.getData();

					try {
						String path = getRealPathFromURI(uri);
						filepath.setText(path);

					} catch (Exception e) {
						Log.e("FileSelectorTestActivity",
								"File select error CREATEACCOUNT", e);
					}
				}

			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
	/**
	 * This callback method will be invoked when the user selects up navigation
	 * icon from the action bar
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, HomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	public String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(contentUri, proj, null,
				null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	public void clearFields() {
		fname.setText("");
		lname.setText("");
		email.setText("");
		mobile.setText("");
		landline.setText("");
		username.setText("");
		password.setText("");
		filepath.setText("");
		username.setText("");
		password.setText("");
	}

	// Asynctask
	public class Create extends AsyncTask<Void, Void, Void> {

		private final ProgressDialog dialog = new ProgressDialog(
				RegisterBuyer.this);
		boolean results;

		protected void onPreExecute() {

			this.dialog.setMessage("Loading...");
			this.dialog.show();
		}

		protected Void doInBackground(final Void... unused) {

			String firstname = fname.getText().toString();
			String lastname = lname.getText().toString();
			String emailAddress = email.getText().toString();
			String mob = mobile.getText().toString();
			String land = landline.getText().toString();
			String user = username.getText().toString();
			String pass = password.getText().toString();

			String file = filepath.getText().toString().trim();
			String filename = new File(file).getName();

			con = new FTPClient();

			try {

				if ((file != "")) {

					results = consume.AddLead(firstname, lastname, mob, land,
							emailAddress, 0, user, pass, "http://" + host
									+ folderLocation + filename);

					Log.v("choya", "nesud" + filename);

					if (results) {

						con.connect(host);

						if (con.login(ftpuser, ftppass)) {

							con.enterLocalPassiveMode(); // important!
							con.setFileType(FTP.BINARY_FILE_TYPE);

							BufferedInputStream buffIn = null;
							buffIn = new BufferedInputStream(
									new FileInputStream(new File(file)), 8192);

							boolean result = con.storeFile(saveLocation
									+ folderLocation + filename, buffIn);
							buffIn.close();
							if (result)
								Log.v("upload result", "succeeded");
							con.logout();
							con.disconnect();

						}

					}

				} else {
					results = consume.AddLead(firstname, lastname, mob, land,
							emailAddress, 0, user, pass, "http://" + host
									+ saveLocation + filename);
				}
				// Toast.makeText(getActivity(), "Created!",
				// Toast.LENGTH_SHORT).show();

			} catch (Exception e) {
				Log.e("", "", e);
			}

			return null;
		}

		protected void onPostExecute(Void result) {
			if (results) {
				Toast.makeText(getApplicationContext(), "Success",
						Toast.LENGTH_SHORT).show();
				startActivity(new Intent(getApplicationContext(),
						LoginActivity.class));
				finish();
			} else {
				Toast.makeText(getApplicationContext(), "cannot be done",
						Toast.LENGTH_SHORT).show();
			}

			if (this.dialog != null) {
				this.dialog.dismiss();
			}
		}
	}

}
